#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import rospy
import requests
import json
import types
import time
from pymongo import MongoClient
from std_msgs.msg import String
from manager.msg import *
# storeId = "16090102"
# headers = {'Content-Type': 'application/x-www-form-urlencoded'}

currentUser = {}

pub_wakup = rospy.Publisher('qrcode_wakeup', String, queue_size=10)
aiui_tts = rospy.Publisher('tts', String, queue_size=1)
pub_guide = rospy.Publisher('guide', Pose, queue_size=10)

def json_get(json, l_key, default):  
    ret = json
    for k in l_key:
        if type(k) is types.IntType:
            if k < 0 : return default
            if not (type(ret) is types.ListType): return default
            if len(ret) <= k: return default
        elif type(k) is types.StringType:
            if not (type(ret) is types.DictType): return default
            if not ret.has_key(k): return default
        else:
            return default
        ret = ret[k]
    return ret

# def http_request(data):    
#     # send_data['query'] = data.data
#     r = requests.get('http://www.lincson.cn/wxhandctrl/api/pos.api?method=vipmember.matching&storeId={0}&openId={1}'.format(storeId, data.data), headers=headers)
#     if r.status_code == 200:

#         ret = r.json()
#         if ret == {}:
#             aiui_tts.publish("请先注册会员!")
#             return
#         # if r.json

#         currentUser = ret
#         pub_wakup.publish("")
#         time.sleep(2)
        
#         # print json_get(ret, ['vipmember', 'guestName'], "").encode('utf-8')
#         greeting_str = json_get(ret, ['vipmember', 'guestName'], "").encode('utf-8') + "你好"
#         # print greeting_str
#         aiui_tts.publish(greeting_str)
#         # todo say hello to user
#         # ret = r.json()
#         # print ret

def wakeup_robot(data):
    msg = json.loads(data.data)
    global currentUser
    currentUser = msg
    name = json_get(currentUser, ['user_infos', 'name'], "")
    balance = json_get(currentUser, ['user_infos', 'balance'], 0)
    room_id = json_get(currentUser, ['reservation', 'room_id'], 0)
    pub_wakup.publish("")
    time.sleep(2)
    aiui_tts.publish("亲爱的{0}".format(name.encode('utf-8')))
    # pass

def speak_info(data):
    global currentUser
    name = json_get(currentUser, ['user_infos', 'name'], "")
    balance = json_get(currentUser, ['user_infos', 'balance'], 0)
    points = json_get(currentUser, ['user_infos', 'points'], 0)
    consumption = json_get(currentUser, ['user_infos', 'sum_of_consumption'], 0)
    room_id = json_get(currentUser, ['reservation', 'room_id'], 0)
    info_type = data.data
    str = ""
    if info_type == "get_point":
        str = "你的积分是{0}".format(points)
    elif info_type == "get_balance":
        str = "你的余额是{0}".format(balance)
    if info_type == "get_consumption":
        str = "你的消费金额是{0}".format(consumption)
    if info_type == "get_room":
        if room_id > 0:
            str = "你预订的是{0}房".format(room_id)
        else:
            str = "你没有预订"
    aiui_tts.publish(str)
    # pass

def ktv_guide(data):
    db = MongoClient().eveapitest
    global currentUser
    # print json_get(currentUser, ['reservation', 'room_id'], 0)
    room_id = json_get(currentUser, ['reservation', 'room_id'], 0)
    if room_id == 0:
        aiui_tts.publish("你没有预订")
        return

    p = db.pose.find_one({
        # "name": slots['value']
        "name": room_id
    }, {"name": 1,
        "x": 1,
        "y": 1,
        "yaw": 1})
    if p:
        pose = Pose()
        pose.name = p["name"]
        pose.x = p["x"]
        pose.y = p["y"]
        pose.yaw = p["yaw"]
        pub_guide.publish(pose)
        # pub_unknow.publish("好的,跟我走吧")
        # time.sleep(4)
        # pub_unknow.publish(infos[pose.name.encode('utf-8')])
    else:
        aiui_tts.publish("没有这个地方")

def aiui_sleep(data):
    global currentUser
    currentUser = {}
    pass

def listener():
    rospy.init_node('userinfo', anonymous=True)
    rospy.Subscriber("qrcode", String, wakeup_robot)
    rospy.Subscriber("speak_info", String, speak_info)
    rospy.Subscriber("ktv_guide", String, ktv_guide)
    rospy.Subscriber("sleep", String, aiui_sleep)
    rospy.spin()

if __name__ == '__main__':
    listener()